<template>
  <div class="image-wrap" v-loading="loading">
    <div class="body-header" style="margin-bottom: 10px;">
      <div class="status-wrap"><span>正常: </span><span class="circle"></span></div>
      <div class="status-wrap"><span>未点检: </span><span class="circle not-checked"></span></div>
      <div class="status-wrap"><span>未更换: </span><span class="circle not-replaced"></span></div>
    </div>
    <div class="svg-wrapper"  ref="svgWrapper"></div>
  </div>
  <RollDetails :param="currentParam" v-model="detailsVisible"></RollDetails>
</template>

<script setup lang="ts">
import { ref, defineProps, nextTick } from 'vue'
import { getRollStatus } from '/@/api/rollPosImage'
import RollDetails from '/@/views/common/RollPosImage/RollDetails.vue';

const props = defineProps<{
  rGroup: string
  svgUrl: string
}>()
let pendingChangeList: { line?: string; rGroup?: string; area?: string; pos?: string; rType?: string;[key: string]: any }[] = []
let pendingCheckList: { line?: string; rGroup?: string; area?: string; pos?: string; rType?: string;[key: string]: any }[] = []

const svgWrapper = ref<HTMLElement | HTMLElement[] | null>(null)
const loading = ref<boolean>(false)
const currentParam = ref<{ line: string; rGroup: string, area: string, pos: string, rType: string }>({
  line: '',
  rGroup: '',
  area: '',
  pos: '',
  rType: ''
})
const detailsVisible = ref<boolean>(false)

const loadAndInsertSvg = async () => {
  await nextTick()

  if (!props.svgUrl) {
    console.log('2280RollPosImage: svgUrl 为空')
    return
  }
  try {
    console.log('2280RollPosImage: 开始加载 SVG:', props.svgUrl)
    const res = await fetch(props.svgUrl)

    const svgText = await res.text()
    const wrapper = svgWrapper.value as HTMLElement
    if (!wrapper) {
      console.log('2280RollPosImage: svgWrapper 为空')
      return
    }
    wrapper.innerHTML = svgText
    console.log('2280RollPosImage: SVG 内容已插入到 DOM')

    applyHighlight(wrapper)
    bindClickEvents(wrapper)
  } catch (error) {
    console.log('2280RollPosImage: 加载 SVG 失败:', error);
  } 
}

const loadData = async () => {
  const { data: { data } } = await getRollStatus({ line: '三分厂', rGroup: props.rGroup });
  pendingChangeList = data?.pendingChangeList || [];
  pendingCheckList = data?.pendingCheckList || [];
}

const applyHighlight = (wrapper: HTMLElement) => {
  const nodes = wrapper.querySelectorAll('circle, ellipse, path')
  nodes.forEach(node => {
    const el = node as HTMLElement
    const line = node.getAttribute('line') || ''
    const rGroup = node.getAttribute('rgroup') || ''
    const area = node.getAttribute('area') || ''
    const pos = node.getAttribute('pos') || ''
    const rType = node.getAttribute('rtype') || ''
    
    const needChange = pendingChangeList.some(i => i.line === line && i.rGroup === rGroup && i.area === area && i.pos === pos && i.rType === rType)
    const needCheck = pendingCheckList.some(i => i.line === line && i.rGroup === rGroup && i.area === area && i.pos === pos && i.rType === rType)

    if (line && rGroup && area && pos && rType) {
      el.style.cursor = 'pointer'
      el.style.fillOpacity = '1'
      el.style.fill = needChange ? '#e11735' : needCheck ? '#ee7616' : '#00FF00'
    }
  })
}

const bindClickEvents = (wrapper: HTMLElement) => {
  const nodes = wrapper.querySelectorAll('circle, ellipse, path')
  console.log('2280RollPosImage: 找到可点击元素数量:', nodes.length)
  let boundCount = 0
  nodes.forEach((node, index) => {
    const line = node.getAttribute('line') || ''
    const rGroup = node.getAttribute('rgroup') || ''
    const area = node.getAttribute('area') || ''
    const pos = node.getAttribute('pos') || ''
    const rType = node.getAttribute('rtype') || ''

    if (line && rGroup && area && pos && rType) {
      // 设置鼠标样式
      (node as HTMLElement).style.cursor = 'pointer'
      
      node.addEventListener('click', (event) => {
        event.stopPropagation() // 阻止事件冒泡
        console.log('2280RollPosImage: 辊子被点击:', { line, rGroup, area, pos, rType })
        currentParam.value = { line, rGroup, area, pos, rType };
        detailsVisible.value = true
        console.log('2280RollPosImage: 设置 detailsVisible 为 true')
      })
      boundCount++
    }
  })
  console.log('2280RollPosImage: 成功绑定点击事件的辊子数量:', boundCount)
}


onMounted(async () => {
  try {
    loading.value = true
    await loadData()
    await loadAndInsertSvg()
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false
  }
})

</script>
<style lang="scss" scoped>
.image-wrap {
  width: 100%;
  height: 100%;
  position: relative;
  :deep(.el-loading-mask){
    background-color: rgba(0,0,0,0.4)
  }
  .body-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    gap: 10px;
    padding: 24px 24px;
    .status-wrap {
      display: flex;
      align-items: center;
      gap: 10px;

      span {
        margin-right: 5px;
        color: #fff;
      }

      .circle {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        background-color: #00FF00;

        &.not-checked {
          background-color: #ee7616;
        }

        &.not-replaced {
          background-color: #e11735;
        }
      }
    }
  }

  .svg-wrapper {
    width: 100%;
    padding: 14px;
    height: 100%;
    margin-bottom: 40px;
    overflow: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    object-fit: contain;
    scrollbar-width: none;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
      display: none;
    }

    :deep(svg) {
      width: 100%;
      height: 100%;
    }
  }

}
</style>
